//
//  SEGShowAuthCodeViewController.m
//  SEGUhomeStandard
//
//  Created by 乔杨 on 2019/4/9.
//  Copyright © 2019 刘山. All rights reserved.
//

#import "SEGShowAuthCodeViewController.h"
#import "SEGSettingPasswordViewController.h"

#import "SEGAuthCodeView.h"

#import "SEGShowAuthCodeViewModel.h"

@interface SEGShowAuthCodeViewController ()

/** 大标题 */
@property (nonatomic, strong) SEGBigNavigationView *bigNavView;
/** 手机号Lab */
@property (nonatomic, strong) UILabel *phoneLab;
/** 虚拟输入框(唤醒键盘使用) */
@property (nonatomic, strong) UITextField *authCodeTF;
/** 获取验证码 */
@property (nonatomic, strong) UIButton *refreshCodeBtn;
/** 语音验证码 */
@property (nonatomic, strong) SEGLabel *voiceCodeLab;
/** 下一步 */
@property (nonatomic, strong) UIButton *nextBtn;
/// 验证码视图
@property (nonatomic, strong) SEGAuthCodeView *codeView;

/// 语音验证码是否可点击
@property (nonatomic, assign) BOOL voiceEnabled;
/// 定时器取消
@property (nonatomic, strong) RACDisposable *disposable;
/// viewModel
@property (nonatomic, strong) SEGShowAuthCodeViewModel *viewModel;

@end

@implementation SEGShowAuthCodeViewController

- (void)dealloc {
    [self.disposable dispose];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_W;
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    [self.bigNavView setTitleWithString:@"验证码已发送至"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notification_textFieldChanged:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
    [self createUI];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.authCodeTF becomeFirstResponder];
    });
    
    // 重新发送按钮 定时器
    [self timer_refreshauthCode];
}

#pragma mark - Load Data
// 获取验证码
- (void)refresh_authCode {
    // 唤起验证码弹窗
    WeakSelf;
    self.codeView.confirmBlock = ^(NSString *code, NSString *randomToken) {
        weakSelf.code = code;
        weakSelf.randomToken = randomToken;
        RACTuple *tuple = RACTuplePack(weakSelf.phoneStr, weakSelf.code, weakSelf.randomToken);
        [weakSelf.viewModel.smsCodeCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
            if (x.boolValue) {
                [SVProgressHUD show];
            } else {
                [SVProgressHUD dismiss];
            }
        }];
        [[weakSelf.viewModel.smsCodeCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
            [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
            // 重新倒计时
            [weakSelf timer_refreshauthCode];
            // 关闭验证码弹窗
            [weakSelf.codeView dismiss];
        } error:^(NSError * _Nullable error) {
            // 失败就刷新验证码
            [weakSelf.codeView refreshCodeImg];
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        }];
    };
    [self.codeView show];
}

// 获取语音验证码
- (void)getVoiceCode {
    RACTuple *tuple = RACTuplePack(self.phoneStr, self.code, self.randomToken, @"register");
    [self.viewModel.soundCodeCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    @weakify(self);
    [[self.viewModel.soundCodeCommand execute:tuple] subscribeNext:^(NSString *message) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:message withtime:1];
        // 重新倒计时
        [self timer_refreshauthCode];
        // 关闭图形验证码弹窗
        [self.codeView dismiss];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        // 失败就刷新验证码
        [self.codeView refreshCodeImg];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 检验 短信/语音验证码
- (void)check_SMSCode {
    RACTuple *tuple = RACTuplePack(self.phoneStr, self.authCodeTF.text);
    @weakify(self);
    [self.viewModel.validateCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        @strongify(self);
        if (x.boolValue) {
            [SVProgressHUD show];
            self.nextBtn.enabled = NO;
        } else {
            [SVProgressHUD dismiss];
            self.nextBtn.enabled = YES;
        }
    }];
    [[self.viewModel.validateCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        SEGSettingPasswordViewController *vc = [SEGSettingPasswordViewController new];
        vc.phoneStr = self.phoneStr;
        vc.randomToken = self.randomToken;
        vc.smsCode = self.authCodeTF.text;
        [self.navigationController pushViewController:vc animated:YES];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - UI
- (void)createUI {
    [self.view addSubview:self.phoneLab];
    CGFloat phone_W = [SEGUtils getWidthWithFontSize:15 height:16 text:self.phoneLab.text];
    [self.phoneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bigNavView.mas_bottom);
        make.left.equalTo(self.view).mas_offset(30);
        make.height.mas_equalTo(16);
        make.width.mas_equalTo(ceil(phone_W));
    }];
    // 重新发送
    [self.view addSubview:self.refreshCodeBtn];
    [self.refreshCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(self.phoneLab);
        make.left.equalTo(self.phoneLab.mas_right).mas_offset(25);
    }];
    // 虚拟输入框
    [self.view addSubview:self.authCodeTF];
    // 验证码输入框
    for (int i=0; i<4; i++) {
        UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        codeBtn.tag = (i+1)*100;
        codeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.f];
        [codeBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
        codeBtn.layer.borderColor = kColor_L2.CGColor;
        codeBtn.layer.borderWidth = 1.f;
        codeBtn.layer.cornerRadius = 5;
        codeBtn.layer.masksToBounds = YES;
        codeBtn.backgroundColor = [UIColor seg_setColorWithAny:kColor_W dark:UIColor.blackColor];
        [codeBtn addTarget:self
                    action:@selector(authCodeTFBecomeFirstResponder)
          forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:codeBtn];
        CGFloat left_x = 30+(50+20)*i;
        [codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.phoneLab.mas_bottom).mas_offset(45);
            make.left.equalTo(self.view).mas_offset(left_x);
            make.width.height.mas_equalTo(50);
        }];
    }
    [self.view addSubview:self.voiceCodeLab];
    [self.voiceCodeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneLab.mas_bottom).mas_offset(110);
        make.left.equalTo(self.view).mas_offset(30);
        make.right.equalTo(self.view).mas_offset(-30);
        make.height.mas_equalTo(14+20);
    }];
    [self.view addSubview:self.nextBtn];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.voiceCodeLab.mas_bottom).mas_offset(110*kScaleWidth);
        make.right.equalTo(self.view.mas_right).mas_offset(-30);
        make.width.mas_equalTo(125);
        make.height.mas_equalTo(44);
    }];
}

#pragma mark - UITextFieldTextDidChangeNotification
- (void)notification_textFieldChanged:(NSNotification *)notification {
    if (self.authCodeTF.text.length > 4) { // 4位限制
        self.authCodeTF.text = [self.authCodeTF.text substringToIndex:4];
    }
    for (int i=0; i<4; i++) { // 清空
        UIButton *codeBtn = (UIButton *)[self.view viewWithTag:(i+1)*100];
        [codeBtn setTitle:@"" forState:UIControlStateNormal];
    }
    for (int i=0; i<self.authCodeTF.text.length; i++) { // 刷新展示框
        UIButton *codeBtn = (UIButton *)[self.view viewWithTag:(i+1)*100];
        NSString *str = [self.authCodeTF.text substringWithRange:NSMakeRange(i,1)];
        [codeBtn setTitle:str forState:UIControlStateNormal];
    }
    self.nextBtn.enabled = self.authCodeTF.text.length >= 4 ? YES:NO;
}

#pragma mark - Timer
- (void)timer_refreshauthCode {
    [self.disposable dispose];
    // 获取语音验证码&重新发送按钮置灰&不可点击
    self.refreshCodeBtn.enabled = NO;
    self.voiceEnabled = NO;
    [self voiceCodeLab_changeColor:kColor_3];
    
    __block NSInteger countdownNum = 59;
    @weakify(self);
    [self.refreshCodeBtn setTitle:@"(60s)" forState:UIControlStateDisabled];
    self.disposable = [[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
        @strongify(self);
        NSString *title = [NSString stringWithFormat:@"(%lds)", countdownNum];
        [self.refreshCodeBtn setTitle:title forState:UIControlStateDisabled];
        
        if (countdownNum <= 0) { // 倒计时结束
            self.refreshCodeBtn.enabled = YES;
            self.voiceEnabled = YES;
            [self voiceCodeLab_changeColor:kColor_S3];
            [self.disposable dispose];
        }
        countdownNum --;
    }];
}

#pragma mark - Event
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)authCodeTFBecomeFirstResponder {
    [self.authCodeTF becomeFirstResponder];
}

#pragma mark - Getter
- (SEGBigNavigationView *)bigNavView {
    if (!_bigNavView) {
        _bigNavView = [[SEGBigNavigationView alloc] initWithType:SEGBigNavBar_backBtn];
        _bigNavView.frame = CGRectMake(0, 0, LYScreenWidth(), kBackBtn_BigNavHeight);
        _bigNavView.fontSize = 30;
        [self.view addSubview:_bigNavView];
    }
    return _bigNavView;
}
- (UILabel *)phoneLab {
    if (!_phoneLab) {
        _phoneLab = [[UILabel alloc] init];
        _phoneLab.textColor = kColor_3;
        _phoneLab.font = kFont_15;
        _phoneLab.text = [NSString stringWithFormat:@"手机号%@",_phoneStr];
    }
    return _phoneLab;
}
- (UIButton *)refreshCodeBtn {
    if (!_refreshCodeBtn) {
        _refreshCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _refreshCodeBtn.backgroundColor = kColor_W;
        [_refreshCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        _refreshCodeBtn.titleLabel.font = kFont_13;
        [_refreshCodeBtn setTitleColor:kColor_S3
                              forState:UIControlStateNormal];
        [_refreshCodeBtn setTitleColor:kColor_3
                              forState:UIControlStateDisabled];
        [_refreshCodeBtn addTarget:self
                            action:@selector(refresh_authCode)
                  forControlEvents:UIControlEventTouchUpInside];
    }
    return _refreshCodeBtn;
}
- (SEGLabel *)voiceCodeLab {
    if (!_voiceCodeLab) {
        _voiceCodeLab = [[SEGLabel alloc] init];
        _voiceEnabled = YES;
        [self voiceCodeLab_changeColor:kColor_S3];
    }
    return _voiceCodeLab;
}
- (void)voiceCodeLab_changeColor:(UIColor *)color {
    NSString *str1 = @"收不到验证码？试试";
    NSString *str2 = @"语音验证码";
    NSString *str = [NSString stringWithFormat:@"%@%@",str1,str2];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str];
    text.yy_font = kFont_13;
    text.yy_color = kColor_3;
    WeakSelf;
    NSRange range = [str rangeOfString:str2];
    [text yy_setTextHighlightRange:range
                             color:color
                   backgroundColor:[UIColor clearColor]
                         tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
                            if (self.voiceEnabled) {
                                 // 唤起图形验证码弹窗
                                 weakSelf.codeView.confirmBlock = ^(NSString *code, NSString *randomToken) {
                                     weakSelf.code = code;
                                     weakSelf.randomToken = randomToken;
                                     [weakSelf getVoiceCode];
                                 };
                                 [weakSelf.codeView show];
                             }
                         }];
    self.voiceCodeLab.attributedText = text;
}
- (UITextField *)authCodeTF {
    if (!_authCodeTF) {
        _authCodeTF = [[UITextField alloc] init];
        _authCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _authCodeTF;
}
- (UIButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [_nextBtn setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [_nextBtn setBackgroundImage:[UIImage imageWithColor:kColor_L2] forState:UIControlStateDisabled];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextBtn.titleLabel.font = kFont_16;
        [_nextBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
        [_nextBtn setTitleColor:[UIColor seg_setColorWithAny:kColor_W dark:kColor_C] forState:UIControlStateDisabled];
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.layer.cornerRadius = 22;
        [_nextBtn addTarget:self
                     action:@selector(check_SMSCode)
           forControlEvents:UIControlEventTouchUpInside];
        _nextBtn.enabled = NO;
    }
    return _nextBtn;
}

- (SEGAuthCodeView *)codeView {
    if (!_codeView) {
        _codeView = [SEGAuthCodeView new];
        _codeView.hidden = YES;
        _codeView.style = SEGAuthCodeViewSecurityStyle;
        [[UIApplication sharedApplication].delegate.window addSubview:_codeView];
    }
    return _codeView;
}
- (SEGShowAuthCodeViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGShowAuthCodeViewModel new];
    return _viewModel;
}

@end
